package com.qcnh.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import unil.Result;
import unil.RedisConstains;
import unil.UserThread;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拦截器取到请求先进行判断，如果是OPTIONS请求，则放行
        if("OPTIONS".equals(request.getMethod().toUpperCase())) {
            System.out.println("Method:OPTIONS");
            return true;
        }
        //从请求头中拿token
        String stoken = request.getHeader("stoken");
        //如果没传stoken，直接拦截
        if (stoken==null){
            Result ok = Result.ok(401, "登录失败", null);
            ObjectMapper objectMapper = new ObjectMapper();
            response.setContentType("application/json");
            response.setStatus(200); // 设置状态码为401
            try {
                objectMapper.writeValue(response.getOutputStream(), ok);
            } catch (IOException e) {
                // 处理写入错误（通常不会发生，除非有严重的IO问题）
                e.printStackTrace();
            }
            return false;
        }
        Integer uid = (Integer) redisTemplate.opsForValue().get(RedisConstains.LOGIN_USER_KEY+stoken);
        if (uid == null) {//根据token查用户，没有则没有登录

            Result ok = Result.ok(401, "登录失败", null);
            ObjectMapper objectMapper = new ObjectMapper();
            response.setContentType("application/json");
            response.setStatus(200); // 设置状态码为401
            try {
                objectMapper.writeValue(response.getOutputStream(), ok);
            } catch (IOException e) {
                // 处理写入错误（通常不会发生，除非有严重的IO问题）
                e.printStackTrace();
            }
            return false;
        }
        UserThread.addUser(uid.toString());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
